package apralms

import org.springframework.dao.DataIntegrityViolationException

class ProductController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
        redirect(action: "list", params: params)
    }

    def list() {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [productInstanceList: Product.list(params), productInstanceTotal: Product.count()]
    }

    def create() {
        [productInstance: new Product(params)]
    }

    def save() {
        def productInstance = new Product(params)
		
		productInstance.classParas = getParas(productInstance)
		
        if (!productInstance.save(flush: true)) {
            render(view: "create", model: [productInstance: productInstance])
            return
        }

		updateProjectSystemParas(productInstance)
		
		flash.message = message(code: 'default.created.message', args: [message(code: 'product.label', default: 'Product'), productInstance.id])
        redirect(controller: "system", action: "show", id: productInstance.system.id)
    }

    def show() {
        def productInstance = Product.get(params.id)
        if (!productInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'product.label', default: 'Product'), params.id])
            redirect(action: "list")
            return
        }

        [productInstance: productInstance]
    }

    def edit() {
        def productInstance = Product.get(params.id)
        if (!productInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'product.label', default: 'Product'), params.id])
            redirect(action: "list")
            return
        }

        [productInstance: productInstance]
    }

    def update() {
        def productInstance = Product.get(params.id)
        if (!productInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'product.label', default: 'Product'), params.id])
            redirect(action: "list")
            return
        }

        if (params.version) {
            def version = params.version.toLong()
            if (productInstance.version > version) {
                productInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'product.label', default: 'Product')] as Object[],
                          "Another user has updated this Product while you were editing")
                render(view: "edit", model: [productInstance: productInstance])
                return
            }
        }

        productInstance.properties = params
		productInstance.classParas = getParas(productInstance)
        updateProjectSystemParas(productInstance)

        if (!productInstance.save(flush: true)) {
            render(view: "edit", model: [productInstance: productInstance])
            return
        }
		
		flash.message = message(code: 'default.updated.message', args: [message(code: 'product.label', default: 'Product'), productInstance.id])
        redirect(action: "show", id: productInstance.id)
    }

    def delete() {
        def productInstance = Product.get(params.id)
        if (!productInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'product.label', default: 'Product'), params.id])
            redirect(action: "list")
            return
        }

        try {
            productInstance.delete(flush: true)
			flash.message = message(code: 'default.deleted.message', args: [message(code: 'product.label', default: 'Product'), params.id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
			flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'product.label', default: 'Product'), params.id])
            redirect(action: "show", id: params.id)
        }
    }
	
	/**
	 * 更新项目及系统参数集
	 * @param productInstance
	 * @return
	 */
	def updateProjectSystemParas(Product productInstance){
		def projectParaSet = [] as Set
		def systemParaSet = [] as Set
		def productParaSet = [] as Set
		
		productInstance.project.classParas.split(',').each{
			if(!it.equals('')) projectParaSet << it
		}
		productInstance.system.classParas.split(',').each {
			if(!it.equals('')) systemParaSet << it			
		}
		productInstance.classParas.split(',').each{
			if(!it.equals('')) productParaSet << it
		}
		
		productParaSet.each {
			projectParaSet << it
			systemParaSet << it
		}
		productInstance.project.classParas = (projectParaSet as Set).toString().replace('[', '').replace(']','').replace(' ', '')
		productInstance.system.classParas = (systemParaSet as Set).toString().replace('[', '').replace(']','').replace(' ', '')
	}
	
	/**
	 * 获取参数字符串
	 * @param productInstance
	 * @return
	 */
	def getParas(Product productInstance){		
		def paraSet = [] as Set;
		
		// 获取基本参数集合
		def classParasForBase = ClassParameter.findAll{
			type == "基本可靠性参数"
			
			class5 == productInstance.class5
			class6 == productInstance.class6
			class7 == productInstance.class7
			class8 == productInstance.class8
		}
		
		// 获取寿命参数集合
		def classParasForLife = ClassParameter.findAll{
			type == "寿命参数"
			
			class1 == productInstance.class1
			class2 == productInstance.class2
			class3 == productInstance.class3
			class4 == productInstance.class4
		}
		
		classParasForBase.each {
			it.paras.split(",").each { paraName ->
				paraSet << paraName
			}
		}
		
		classParasForLife.each {
			it.paras.split(",").each { paraName->
				paraSet << paraName
			}
		}
		
		return paraSet.toString().replace('[', '').replace(']','').replace(' ', '')
	}
	
	/**
	 * 分配参数分配
	 */
	def assignParameters() {
		def productInstance = Product.get(params.id)

		// 清除原有参数集
		def query = ProductIndex.where {
			product == productInstance
		}
		int total = query.deleteAll()
		
		// 获取基本参数集合
		def classParametersForBase = ClassParameter.findAll{
			type == "基本可靠性参数"
			
			class5 == productInstance.class5
			class6 == productInstance.class6
			class7 == productInstance.class7
			class8 == productInstance.class8
		}
		
		// 获取寿命参数集合
		def classParametersForLife = ClassParameter.findAll{
			type == "寿命参数"
			
			class1 == productInstance.class1
			class2 == productInstance.class2
			class3 == productInstance.class3
			class4 == productInstance.class4
		}
		
		classParametersForBase.each {
			def paraString = it.paras.split(",")

			paraString.each{ paraName ->
				def parameterInstance = Parameter.findByName(paraName)
				def productIndexInstance = new ProductIndex(code:it.code,name:it.name, product:productInstance, parameter:parameterInstance)
				productIndexInstance.save()
			}
		}
		
		classParametersForLife.each {
			def paraString = it.paras.split(",")
			
			paraString.each { paraName->
				def parameterInstance=Parameter.findByName(paraName)
				def productIndexInstance = new ProductIndex(code:it.code,name:it.name, product:productInstance, parameter:parameterInstance)
				productIndexInstance.save()
			}
		}
		
		flash.message = message(code: 'assignParameters.finished.message', args: [message(code: 'product.label', default: 'Product'), productInstance.name])
		redirect(action: "list", id: params.id)
	}
}
